/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.reddys.rad.inventory.controller;

import com.reddys.rad.inventory.db.Product;
import com.reddys.rad.inventory.db.PurchaseOrder;
import com.reddys.rad.inventory.db.PurchaseOrderDetails;
import com.reddys.rad.inventory.db.Vendor;
import com.reddys.rad.inventory.service.PurchaseOrderService;
import com.reddys.rad.inventory.utils.AutoCompleteTextboxListener;
import com.reddys.rad.inventory.utils.EditingCell;
import com.reddys.rad.inventory.utils.EntityManagerImpl;
import com.reddys.rad.inventory.utils.Utilities;
import eu.schudt.javafx.controls.calendar.DatePicker;
import inventory.Inventory;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;
import javax.persistence.EntityManager;

/**
 * FXML Controller class
 *
 * @author REDDYS
 */
public class PurchaseOrderController implements Initializable {

    EntityManager em = null;
    Stage stage;
    private final ObservableList<PurchaseOrderDetails> data =  FXCollections.observableArrayList();
    private  ObservableList dataList =  FXCollections.observableArrayList();
    Logger log = Utilities.getLogger("PurchaseOrderController");
    @FXML
    TableView tableView;
    
    @FXML
    ComboBox vendor;
    
    @FXML
    TextField purchaseOrderID;
    
    @FXML
    TextField purchaseOrderDate;
    
    @FXML
    TextField contactPerson;
        
    @FXML
    TextField phone;
        
    @FXML
    TextField location;
    
    @FXML
    VBox vbox1;
    
    @FXML
    AnchorPane datePickerAnchorPane;
    
    DatePicker birthdayDatePicker = new  DatePicker();
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
       this.stage = Inventory.stage;
       tableView.setEditable(true);
       purchaseOrderID.setEditable(false);
       loadTableColumns(tableView);
       addEmptyRows();
         birthdayDatePicker = new DatePicker(Locale.ENGLISH);
         birthdayDatePicker.setDateFormat(new SimpleDateFormat("dd-MM-yyyy"));
         birthdayDatePicker.getCalendarView().todayButtonTextProperty().set("Today");
         birthdayDatePicker.getCalendarView().setShowWeeks(false);
         birthdayDatePicker.getStylesheets().add("/DatePicker.css");
         datePickerAnchorPane.getChildren().add(birthdayDatePicker);
         DatePicker.setHgrow(birthdayDatePicker, Priority.ALWAYS);
      
         dataList = getPurchaseOrderService().getVendorList();
         vendor.getItems().addAll(dataList);
         vendor.focusedProperty().addListener(new ChangeListener<Boolean>() {
            @Override
            public void changed(ObservableValue observable, Boolean oldValue, Boolean newValue) {
                
                     System.out.println(vendor.getSelectionModel());
                     Vendor sevendor = (Vendor) vendor.getSelectionModel().getSelectedItem();
                     if(sevendor!=null){
                         contactPerson.setText(null);
                         phone.setText(null);
                         location.setText(null);
                      
                     contactPerson.setText(sevendor.getContactperson());
                     phone.setText(sevendor.getContactpersonnumber());
                     location.setText(sevendor.getAddress1()+" "+sevendor.getAddress2()!=null?sevendor.getAddress2():"");
                     }else{
                         contactPerson.setText(null);
                         phone.setText(null);
                         location.setText(null);
                     }
                    
                
            }
        });
      // new  AutoCompleteComboBoxListener(vendor,dataList);
      // new AutoCompleteTextboxListener(purchaseOrderID,dataList);
    }    

    private void loadTableColumns(TableView tableView) {
        tableView.setEditable(true);
       TableColumn productCategory = new TableColumn("Product Category");
        productCategory.setMinWidth(175);
        Callback<TableColumn, TableCell> cellFactory =
             new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell();
                 }
             };
 /*       productCategory.setCellValueFactory(new Callback<CellDataFeatures<PurchaseOrderDetails, String>, String>() {

            @Override
            public String call(CellDataFeatures<PurchaseOrderDetails, String> p) {
               return p.getValue().getProductId().getProductId();
            }
  });*/
        productCategory.setCellFactory(new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("ProductCategory");
                 }
             });
/*        productCategory.setOnEditCommit(
                new EventHandler<TableColumn.CellEditEvent<PurchaseOrderDetails, String>>() {
                     
                    @Override 
                    public void handle(TableColumn.CellEditEvent<PurchaseOrderDetails, String> t) {
                         System.out.println(t);
                        System.out.println("before Setting"+((PurchaseOrderDetails)t.getTableView().getItems().get(t.getTablePosition().getRow())).getProductId());
                        ((PurchaseOrderDetails)t.getTableView().getItems().get(
                                t.getTablePosition().getRow())).setProductId(t.getNewValue());
                        System.out.println("after Setting"+((PurchaseOrderDetails)t.getTableView().getItems().get(t.getTablePosition().getRow())).getProductId());
                    }
                });
 */
        TableColumn productID = new TableColumn("Product ID");
        productID.setMinWidth(125);
        productID.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("productId"));
        productID.setCellFactory(new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                     
                    return new EditingCell("ProductID");
                 }
             });
 /*       productID.setOnEditCommit(
            new EventHandler<CellEditEvent<PurchaseOrderDetails, String>>() {
                @Override
                public void handle(CellEditEvent<PurchaseOrderDetails, String> t) {
                    ((PurchaseOrderDetails) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())
                        ).setProductId(t.getNewValue());
                }
             }
        );
 */
        TableColumn productName = new TableColumn("Product Name");
        productName.setMinWidth(250);
        productName.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("productDescription"));
        
       // productName.setCellFactory(cellFactory);
        
        TableColumn itemCode = new TableColumn("Item Code");
        itemCode.setMinWidth(200);
        itemCode.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("itemCode"));
        //itemCode.setCellFactory(cellFactory);
 
        TableColumn quantity = new TableColumn("Quantity");
        quantity.setMinWidth(150);
        quantity.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("batchCode"));
        quantity.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("Quantity");
                 }
             });
        quantity.setOnEditCommit(
            new EventHandler<CellEditEvent<PurchaseOrderDetails, String>>() {
                @Override
                public void handle(CellEditEvent<PurchaseOrderDetails, String> t) {
                    System.out.println("handle event for quantity");
                    ((PurchaseOrderDetails) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())
                        ).setQuantity(new Double(t.getNewValue()));
                }
             }
        );
        
        TableColumn uom = new TableColumn("Uom");
        uom.setMinWidth(150);
        uom.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("standardUom"));
        uom.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("UOM");
                 }
             });
        
        TableColumn unitPrice = new TableColumn("Unit Price");
        unitPrice.setMinWidth(150);
        unitPrice.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("cost"));
        unitPrice.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("UnitPrice");
                 }
             });
 
        TableColumn qtyReceived = new TableColumn("Quantity Received");
        qtyReceived.setVisible(false);
        qtyReceived.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("discount"));
        qtyReceived.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("Discount");
                 }
             });
        
        TableColumn balanceQty = new TableColumn("balance qty");
         balanceQty.setVisible(false);
        balanceQty.setCellValueFactory(
                new PropertyValueFactory<PurchaseOrderDetails, String>("cost"));
        balanceQty.setCellFactory( new Callback<TableColumn, TableCell>() {
                 public TableCell call(TableColumn p) {
                    return new EditingCell("SubTotal");
                 }
             });
        tableView.getColumns().addAll(productCategory, productID, productName,itemCode, quantity,qtyReceived, balanceQty,uom,unitPrice);
        tableView.setItems(data);
 
    }

    @FXML
    private void addEmptyRows() {
        for(int i=0;i<10;i++){
         data.add(new PurchaseOrderDetails());
        }
    }
    
    @FXML
    private void clearRows() {
        tableView.getItems().clear();
    }
    
    @FXML
    private void save() {
        try{
        if(validateSave()){
        em = EntityManagerImpl.getEntityManager();
            EntityManagerImpl.beginTransaction(em);
        PurchaseOrder  purchaseOrder = new PurchaseOrder();
        purchaseOrder.setPurchaseOrderDate(birthdayDatePicker.getSelectedDate());
        Vendor vendorEntity = (Vendor) vendor.getSelectionModel().getSelectedItem();
        purchaseOrder.setVendorId(vendorEntity.getVendorid());
        purchaseOrder.setVendorLocation(vendorEntity.getCity());
        purchaseOrder.setStatus(location.getText());
        purchaseOrder = getPurchaseOrderService().saveHeader(purchaseOrder,em);
       
       for(int i =0;i<tableView.getItems().size();i++){
        PurchaseOrderDetails purchaseOrderDetails = (PurchaseOrderDetails) tableView.getItems().get(i);
        if(!Utilities.isNull(purchaseOrder.getPurchaseOrderId()) && !Utilities.isNull(purchaseOrderDetails.getProductId())){
                    System.out.println(purchaseOrder.getPurchaseOrderId());
            purchaseOrderDetails.setPurchaseOrderId(purchaseOrder.getPurchaseOrderId());
            purchaseOrderDetails.setQuantityRemaining(purchaseOrderDetails.getQuantity());
            purchaseOrderDetails.setQuantityOrdered(purchaseOrderDetails.getQuantity());
            getPurchaseOrderService().save(purchaseOrderDetails,em);
        }
        purchaseOrderID.setText(purchaseOrder.getPurchaseOrderId());
    
       }
       EntityManagerImpl.commitTransaction(em);
       Utilities.createDialog("Transaction Completed Successfully");
    }
    }catch(Exception e){
        e.printStackTrace();
        log.info(e.getMessage());
        EntityManagerImpl.rollbackTransaction(em);
        Utilities.createDialog("Transaction Failed");
    }
    }
    public PurchaseOrderService getPurchaseOrderService(){
        PurchaseOrderService purchaseOrderService = new PurchaseOrderService();
        return purchaseOrderService;
    }

    private boolean validateSave() {
        boolean purchaseDetailsBoolean = true;
        if(null == birthdayDatePicker.getSelectedDate()){
            Utilities.createDialog("Please Select Purchase Order Date");
            return false;
        }
        
         
        if(vendor.getSelectionModel()!=null){
            Vendor vendorEntity = (Vendor) vendor.getSelectionModel().getSelectedItem();
            if(null == vendorEntity){
            Utilities.createDialog("Please Select Vendor");
            return false;
            }
        }else{
             Utilities.createDialog("Please Select Vendor");
            return false;
        }
        for(int i =0;i<tableView.getItems().size();i++){
        PurchaseOrderDetails purchaseOrderDetails = (PurchaseOrderDetails) tableView.getItems().get(i);
        if(!Utilities.isNull(purchaseOrderDetails.getProductId())){
            purchaseDetailsBoolean = false;
            if(null ==purchaseOrderDetails.getQuantity()) {
                Utilities.createDialog("Please enter Quantity");
                return false;
            }
            if(Utilities.isNull(purchaseOrderDetails.getUom())) {
                Utilities.createDialog("Please enter Uom");
                return false;
            }
        }
        }
        if(purchaseDetailsBoolean){
             Utilities.createDialog("Please Add Atleast one Product");
            return false;
        }
        System.out.println(tableView.getItems().size());
        return true;
    }
    

}
